package com.packtpub.e4.clock.ui.views;


import java.util.TimeZone;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.RowData;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;


public class ClockView extends ViewPart {
    private Combo timezones;

    public ClockView() {
    }

    @Override
    public void createPartControl(Composite parent) {
        // 할당된 리소스 객체 수 확인
        Object[] oo = parent.getDisplay().getDeviceData().objects;
        int c = 0;
        for (Object o : oo) {
            if (o instanceof Color) {
                c++;
            }
        }
        System.out.println("There are " + c + " Color Instances");

        RowLayout layout = new RowLayout(SWT.HORIZONTAL);
        parent.setLayout(layout);

        final ClockWidget clock1 = new ClockWidget(parent, SWT.NONE, new RGB(255, 0, 0));
        clock1.setLayoutData(new RowData(20, 20));
        final ClockWidget clock2 = new ClockWidget(parent, SWT.NONE, new RGB(0, 255, 0));
        final ClockWidget clock3 = new ClockWidget(parent, SWT.NONE, new RGB(0, 0, 255));
        clock3.setLayoutData(new RowData(100, 100));

        String[] ids = TimeZone.getAvailableIDs();
        timezones = new Combo(parent, SWT.DROP_DOWN);
        timezones.setVisibleItemCount(5);
        for (String id : ids) {
            timezones.add(id);
        }

        timezones.addSelectionListener(new SelectionListener() {

            @Override
            public void widgetSelected(SelectionEvent arg0) {
                String z = timezones.getText();
                TimeZone tz = z == null ? null : TimeZone.getTimeZone(z);
                TimeZone dt = TimeZone.getDefault();
                int offset = tz == null ? 0 : (
                        tz.getOffset(System.currentTimeMillis()) - dt.getOffset(System.currentTimeMillis())) / 3600000;
                clock3.setOffset(offset);
                clock3.redraw();
            }

            @Override
            public void widgetDefaultSelected(SelectionEvent arg0) {
                clock3.setOffset(0);
                clock3.redraw();
            }
        });
    }

    @Override
    public void setFocus() {
        timezones.setFocus();
    }
}